<!-- 新建、编辑需求模板 -->
<template>
  <div class="index">
    <pageHeader :title="title" :bread-crumb="breadCrumb" :show-back="true">
      <template #buts>
        <a-button html-type="submit" type="primary" @click="save">{{
          form.template.id && form.template.id > 0 ? '保存' : '添加'
        }}</a-button>
        <a-button @click="cancel">取消</a-button>
      </template>
    </pageHeader>
    <div class="content">
      <div class="title">基础设置</div>
      <a-form
        auto-label-width
        ref="demandTemplateRef"
        layout="vertical"
        :model="form.template"
      >
        <a-form-item
          field="tempName"
          label="模板名称"
          validate-trigger="input"
          required
        >
          <a-input
            v-model="form.template.tempName"
            placeholder="请输入模板名称"
            message="此项必填!"
          />
        </a-form-item>
        <a-form-item field="name" label="单据说明" validate-trigger="input">
          <a-textarea
            v-model="form.template.tempDes"
            placeholder="请输入说明描述该需求，100字以内"
            :max-length="100"
            auto-size
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <!-- <a-form-item field="name" label="设置需求编号规则" validate-trigger="input">
              <a-input v-model="form.name" placeholder="请输入说明描述该需求，100字以内" />
            </a-form-item> -->
        <a-form-item field="name" label="图标" validate-trigger="input">
          <icon-book size="24" @click="iconClick" />
        </a-form-item>
        <!-- <a-form-item class="end-line" field="name" label="启用状态" validate-trigger="blur">
              <a-switch v-model="form.template.state" :checked-value="1" :unchecked-value="2">
                <template #checked> 开 </template>
                <template #unchecked> 关 </template>
              </a-switch>
            </a-form-item> -->
        <div class="title">表单与流程</div>
        <a-form-item label="表单与打印" validate-trigger="blur" required>
          <!--  -->
          <a-input
            ref="inputRef"
            :model-value="formControlName"
            placeholder="请选择"
            message="此项必填!"
            readonly
            @click="formClick"
          />
        </a-form-item>
        <!-- <a-form-item class="end-line" field="name" validate-trigger="blur">
          <a-checkbox value="1">上传并使用自定义打印模板</a-checkbox>
          <span class="set-print-model">点击设置</span>
        </a-form-item>
        <div class="title">规则与适用范围</div>
        <a-form-item field="name" label="适用范围" validate-trigger="blur">
          <a-radio-group v-model="form.template.scopeType" direction="vertical">
            <a-radio :value="1">限定部门或人员适用</a-radio>
            <a-radio :value="2">不限</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          class="end-line"
          field="name"
          label="需求金额可见"
          validate-trigger="blur"
        >
          <a-radio-group
            v-model="form.template.amountViweType"
            direction="vertical"
          >
            <a-radio :value="1">仅当前录入人员和指定人员可见</a-radio>
            <a-radio :value="2">不限</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="评审流程" validate-trigger="blur">
          <a-input
            ref="workFlowInputRef"
            :model-value="workFlowName"
            placeholder="请选择"
            message="此项必填!"
            readonly
            @click="workFlowClick"
          />
        </a-form-item> -->
      </a-form>
    </div>
    <!-- 图标选择弹框 -->
    <a-modal
      v-model:visible="iconModalVisible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template #title> Title </template>
      <div>图标列表</div>
    </a-modal>
    <!-- 表单与流程弹框设置 -->
    <a-modal
      v-model:visible="formModalVisible"
      class="form-modal"
      width="60%"
      :esc-to-close="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template #title>
        <h3>表单与打印</h3>
      </template>
      <div class="tips">不同订单模板类型下的表单无法共享</div>
      <a-button long type="outline" @click="formCreate">
        <template #icon> <icon-plus /> </template>新建表单并使用
      </a-button>
      <div class="meta">
        <div>选择已有表单使用</div>

        <a-input-search
          search-button
          :style="{ width: '320px' }"
          placeholder="请输入名称"
        />
      </div>
      <div class="form-list-content">
        <a-empty v-if="formList.length == 0" />
        <a-radio-group
          v-model="demandCheckValue"
          direction="vertical"
          style="width: 100%"
        >
          <div v-for="item in formList" :key="item.id" class="form-list">
            <a-radio :value="item.id">
              <div class="form-name">{{ item.name }}</div>
              <div class="form-info">
                <span
                  >创建时间：{{
                    `${dayjs(item.createdAt).format('YYYY-MM-DD')}`
                  }}</span
                >
                <span>创建人：{{ item.userName }}</span>
              </div>
            </a-radio>
            <a-space class="btn-group">
              <a-button type="text" @click="edit(item.id)">编辑</a-button>
              <a-button type="text" @click="copyFormProcess(item.id)"
                >复制</a-button
              >
              <a-popconfirm
                content="确定删除吗?"
                @ok="deleteOrderDesignDelPrint(item.id)"
              >
                <a-button type="text">删除</a-button>
              </a-popconfirm>
            </a-space>
          </div>
        </a-radio-group>
      </div>
    </a-modal>
    <!-- 控件表单选择弹框 -->
    <formControlCreate
      ref="formControl"
      :data="data"
      :getTemplateControl="getTemplateControl"
      @saveForm="saveForm"
    ></formControlCreate>
    <workflow
      ref="workFlowRef"
      :workFlowList="workFlowList"
      :flowId="form.template.flowId"
      @update:workFlowList="choiseFlow"
      @createFlow="createFlow"
    >
    </workflow>
    <FlowSet
      ref="flowSetRef"
      :showTemplate="false"
      :conditionForm="conditionForm"
      :data="flowData.list"
      @update:data="saveData"
    ></FlowSet>
  </div>
</template>

<script lang="ts" setup>
  /**sdijsidj */
  import { reactive, ref, nextTick, onMounted, computed, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import uniqueid from 'lodash.uniqueid';
  import dayjs from 'dayjs';
  import {
    getDemandList,
    deleteOrderDesignDel,
    getDemandFromInfo,
    postCopyOrderDesign,
    postDemandTemplate,
    getDemandTemplateInfo,
    putDemandTemplate,
    getDemandTemplateList,
    putOrderDesignMod,
    postOrderDesignAdd,
  } from '@/api/order-management/client-management/demand/demand';
  import { postBasisFlowSearch } from '@/api/home/System settings/basis-flow';
  import {
    postBasisFlow,
    getBasisFlow,
    putBasisFlow,
  } from '@/api/order-management/client-management/order';
  import type { FlowDataType, FlowItem } from '@/types/flow';
  import { useOrderStore } from '@/store';
  import workflow from '../flow/index.vue';
  import FlowSet from '../flow/flow-set.vue';

  const store = useOrderStore();
  const getTemplateControl = ref();
  const active = ref(false);
  const router = useRouter();
  const inputRef = ref();
  const breadCrumb: string[] = ['订单管理', '基础设置', '新建需求'];
  const title = ref('新建需求模板');
  interface ScopeType {
    userStaffId: number;
    userDepartmentId: number;
  }
  interface TemplateType {
    id?: number;
    type: number; // 1需求 2订单
    tempName: string;
    state: number;
    tempDes: string; // 单据说明
    icon: string;
    orderDesignId: number; // 需求模板id
    flowId: number;
    scopeType: number; // 适用范围 1.限定部门或人员适用 2.不限
    amountViweType: number; // 需求金额可见 1.仅当前录入人员和指定人员可见 2.不限
    scope: ScopeType[];
    amountView: ScopeType[];
  }
  interface FormType {
    template: TemplateType;
  }
  const form = reactive<FormType>({
    template: {
      id: undefined,
      type: 3, // 1需求 2订单
      tempName: '',
      state: 2,
      tempDes: '', // 单据说明
      icon: '',
      orderDesignId: 0, // 需求模板id
      flowId: 0,
      scopeType: 0, // 适用范围 1.限定部门或人员适用 2.不限
      amountViweType: 0, // 需求金额可见 1.仅当前录入人员和指定人员可见 2.不限
      scope: [
        { userStaffId: 0, userDepartmentId: 0 }, // 用户id，部门id
      ],
      amountView: [{ userStaffId: 0, userDepartmentId: 0 }],
    },
  });
  const iconModalVisible = ref(false);
  // 切换图标
  const iconClick = () => {
    iconModalVisible.value = true;
  };

  const handleCancel = () => {
    iconModalVisible.value = false;
  };
  const formModalVisible = ref(false);
  interface FormList {
    id: number;
    type: number;
    name: string;
    userId: number;
    userName: string;
    checked: number;
    form: any;
    print: any;
    createdAt?: string;
    updateAt?: string;
    deletedAt?: string;
  }
  const formList = ref<FormList[]>([]); // 表单与打印配置 列表
  const getFormList = () => {
    let params = { type: 3 }; // 默认1 ，需求表单
    formList.value = [];
    getDemandList(params).then((res) => {
      if (res.length > 0) {
        formList.value = res;
      }
    });
  };
  const demandCheckValue = ref(0);
  const formClick = () => {
    getFormList(); // 获取需求模板列表
    demandCheckValue.value = form.template.orderDesignId;
    formModalVisible.value = true;
  };
  const formControl = ref();
  interface DataType {
    id?: number;
    type: number; // 1需求2订单
    name: string;
    form: any[];
    print: any[];
  }
  //控件表单数据
  let data = reactive<DataType>({
    id: undefined,
    type: 3, // 1需求2订单
    name: '新建表单',
    form: [],
    print: [],
  });
  const reset = () => {
    data.id = undefined;
    data.type = 3; // 1需求2订单
    data.name = '新建表单';
    data.form = [];
    data.print = [];
  };
  const mustFormData = [
    {
      show: 1,
      componentType: 'NUMBER-UNIVERSAL',
      code: 'NUMBER-UNIVERSAL',
      props: { placeholder: '请输入文字' },
      name: '订单号',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'number',
    },
    {
      show: 1,
      componentType: 'CLIENT',
      code: 'CLIENT',
      props: { placeholder: '请输入文字' },
      name: '客户名称',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'clientCompanyId',
    },
    {
      show: 1,
      componentType: 'BUSINESS_MANAGER',
      code: 'BUSINESS_MANAGER',
      props: { placeholder: '请输入文字' },
      name: '业务经理',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'userStaffId',
    },
    {
      show: 1,
      componentType: 'ORDER_TIME',
      code: 'ORDER_TIME',
      props: { placeholder: '请输入文字' },
      name: '订单日期',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'orderTime',
    },
    {
      show: 1,
      componentType: 'CLIENT_NUMBER',
      code: 'CLIENT_NUMBER',
      props: { placeholder: '请输入文字' },
      name: '客户编号',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
    },
    {
      show: 1,
      componentType: 'CONTACT_NAME',
      code: 'CONTACT_NAME',
      props: { placeholder: '请输入文字' },
      name: '联系人',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'customerId',
    },
    {
      show: 1,
      componentType: 'CONTACT-NUMBER',
      code: 'CONTACT-NUMBER',
      props: { placeholder: '请输入文字' },
      name: '联系电话',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 2,
      fieldName: 'customerPhone',
    },
    {
      show: 1,
      componentType: 'ADDRESS',
      code: 'ADDRESS',
      props: { placeholder: '请输入文字' },
      name: '联系地址',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 2,
    },
  ];
  // 新建需求表单
  const formCreate = () => {
    reset();
    data.form = mustFormData;
    formControl.value.fullScreen();
    getTemplateControl.value = store.getTemplateControl;
    // nextTick(() => {
    //   reset();
    // });
  };
  // 父组件获取子组件生成的表单id
  const saveForm = async (formData: any) => {
    // 编辑保存表单
    if (formData.id > 0) {
      await putOrderDesignMod(formData);
    } else {
      // 添加
      await postOrderDesignAdd(formData);
    }
    getFormList(); // 控件表单保存，发一次请求
  };
  // 删除表单与打印配置
  const deleteOrderDesignDelPrint = (id: number) => {
    let params = { id };
    deleteOrderDesignDel(params).then((res) => {
      //删除此项，过滤掉
      formList.value = formList.value.filter((val) => {
        return val.id !== id;
      });
      Message.success('删除成功');
    });
  };

  const edit = (formId: number) => {
    formControl.value.fullScreen();
    let params = {
      id: formId,
      type: 3,
    };
    getDemandFromInfo(params).then((res) => {
      // data = cloneDeep(res)
      data.id = formId;
      data.type = 3; // 1需求2订单
      data.name = res.name;
      res.form.forEach((element: any) => {
        // if(isJSON(element.props)){
        element.props = JSON.parse(element.props);
        if (element.values !== '') {
          element.values = JSON.parse(element.values);
        }

        // }
      });
      data.form = res.form;
      data.print = res.print;
    });
  };
  const copyFormProcess = (uid: number) => {
    let params = {
      id: uid,
    };
    postCopyOrderDesign(params).then((res) => {
      getFormList(); // 添加成功，获取一次列表，刷新
    });
  };
  const demandTemplateRef = ref();
  // 保存按钮,判断是否有id，没有是添加需求模板，有是修改
  const save = async () => {
    // 表单规则验证
    await demandTemplateRef.value.validate(async (res: unknown) => {
      if (res === undefined) {
        // 添加或编辑都需要判断一下此份模板状态是否是开启状态
        if (form.template.state === 1) {
          // 应该查询状态开启的模板关闭，没有此接口，则查询全部模板
          getDemandTemplateList({ type: 1 }).then((res) => {
            let template = res.filter((item: any) => {
              return item.state === 1;
            });
            template[0].state = 2;
            // 调用修改接口
            putDemandTemplate(template[0]).then((updateRes) => {
              // 状态修改后
              if (form.template.id) {
                // 编辑
                putDemandTemplate(form.template).then((res) => {
                  Message.success('保存成功');
                  router.back();
                });
              } else {
                // 添加
                postDemandTemplate(form.template).then((item) => {
                  Message.success('添加成功');
                  router.back();
                });
              }
              router.back();
            });
          });
        } else {
          let str = '保存成功';
          if (form.template.id) {
            // 编辑
            let res = await putDemandTemplate(form.template);
            router.back();
          } else {
            // 添加
            let res = await postDemandTemplate(form.template);
            str = '添加成功';
            router.back();
          }
          Message.success(str);
        }
      }
    });
  };

  // 取消按钮
  const cancel = () => {
    router.back();
  };

  const formControlName = ref(''); // 表单控件名称
  const conditionForm = ref([]);
  // 根据控件表单id，获取对应的名称
  const getDemandFromNameById = async (id: number) => {
    let res = await getDemandFromInfo({ id });
    conditionForm.value = res.form;

    formControlName.value = res.name;
  };
  const workFlowName = ref('');
  // 选中流程改变，获取对应审批名称
  const choiseFlow = async (id: number) => {
    form.template.flowId = id;
    let res = await getBasisFlow({ id });
    workFlowName.value = res.name;
  };
  // 获取一份需求模板信息
  const getDemandTemplate = async (id: number | string) => {
    id = Number(id);
    let res = await getDemandTemplateInfo({ id });
    form.template = res;
    getDemandFromNameById(form.template.orderDesignId);
    if (form.template.flowId > 0) {
      choiseFlow(form.template.flowId);
    }
  };

  // const getFormTemplateNameById = () => {};
  onMounted(() => {
    let demandTemplateId = Number(router.currentRoute.value.query.id);
    if (demandTemplateId > 0) {
      getDemandTemplate(demandTemplateId);
    }
    title.value = demandTemplateId > 0 ? '编辑需求模板' : '新建需求模板';
  });

  // 选择控件表单
  const handleOk = () => {
    iconModalVisible.value = false;
    form.template.orderDesignId = demandCheckValue.value;
    getDemandFromNameById(form.template.orderDesignId);
  };
  const workFlowInputRef = ref();
  const workFlowRef = ref();

  const flowSetRef = ref();
  const flowParams = reactive({
    pageIndex: 0,
    pageSize: 999,
    type: 1,
  });
  const workFlowList = reactive({ checkId: 0, data: [] });
  const getFlowList = async () => {
    let res = await postBasisFlowSearch(flowParams);
    workFlowList.data = res.Data;
    workFlowList.checkId = form.template.flowId;
  };
  const workFlowClick = async () => {
    workFlowRef.value.workFlowVisible = true;
    getFlowList();
  };
  let flowData = reactive<FlowDataType>({
    list: {
      type: 1,
      templateId: 0,
      name: '',
      userStaffId: 0,
      userStaffName: '',
      description: '',
      nodeConfig: {
        type: 0,
        name: '发起人',
        sort: 0,
        auditType: 0,
        approverType: 0,
        approverTypeId: 0,
        nodeUserList: [],
        approverIsEmpty: 0,
        conditionNodes: [],
        childNode: null,
      },
      status: 0,
      reCommit: 1,
      updatedUserStaffId: 0,
      updatedUserStaffName: '',
    },
  });
  const resetFlowData = () => {
    flowData.list = {
      type: 1,
      templateId: 0,
      name: '',
      userStaffId: 0,
      userStaffName: '',
      description: '',
      nodeConfig: {
        type: 0,
        name: '发起人',
        sort: 0,
        auditType: 0,
        approverType: 0,
        approverTypeId: 0,
        nodeUserList: [],
        approverIsEmpty: 0,
        conditionNodes: [],
        childNode: null,
      },
      status: 0,
      reCommit: 1,
      updatedUserStaffId: 0,
      updatedUserStaffName: '',
    };
  };
  // 有id编辑，无id添加
  const createFlow = async (id?: number) => {
    if (id && id > 0) {
      let res = await getBasisFlow({ id });
      flowData.list = res;
    } else {
      resetFlowData();
    }
    flowSetRef.value.fullScreen();
  };
  const saveData = async (data: FlowItem) => {
    if (data.id) {
      let res = await putBasisFlow(data);
      Message.success('保存成功');
    } else {
      let res = await postBasisFlow(data);
      Message.success('添加成功');
    }
    getFlowList();
  };
</script>

<style lang="less" scoped>
  .index {
    display: flex;
    flex-direction: column;
    height: 100%;

    .content {
      // height: 400px;
      flex: 1;
      overflow-y: auto;
      margin: 16px;
      padding: 16px;
      border: 1px solid #eee;
      box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.3);
      border-radius: 5px;

      .title {
        font-size: 16px;
        margin-bottom: 10px;
      }

      .end-line {
        padding-bottom: 16px;
        border-bottom: 15px solid #eee;
      }

      .set-print-model {
        margin-left: 16px;
        cursor: pointer;
        color: #409eff;
      }

      .line-box {
        display: flex;
      }
    }
  }

  .form-modal {
    display: flex;
    flex-direction: column;
    height: 100%;

    .tips {
      border-radius: 5px;
      background: rgba(230, 247, 255, 1);
      padding: 5px 10px;
      margin-bottom: 16px;
      font-size: 16px;
    }

    .meta {
      display: flex;
      justify-content: space-between;
      margin: 16px 0;
      font-size: 16px;
    }

    .form-list-content {
      flex: 1;
      overflow: auto;

      .form-list {
        border-bottom: 1px solid #eee;
        padding-bottom: 16px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;

        .form-name {
          font-size: 16px;
        }

        .form-info {
          font-size: 12px;
          color: #666;

          span {
            margin-right: 16px;
          }
        }
      }
    }
  }
</style>
